//
//  WmcFeedbackVM.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/4/1.
//

import RxSwift
import UIKit
import YPBedrock

extension WmcFeedbackVM {
    class CellModel {
        // Lifecycle

        init(title: String,
             style: Style,
             rowHeight: CGFloat = 57,
             actionType: ActionType = .none)
        {
            self.title = title
            self.style = style
            self.rowHeight = rowHeight
            self.actionType = actionType
        }

        // Internal

        enum Style {
            case arrow
            case input
            case textField
        }

        enum ActionType {
            case none
            case sheet
        }

        /// 标题
        var title: String
        /// 样式
        var style: Style
        /// 高度
        var rowHeight: CGFloat
        /// 触发类型
        var actionType: ActionType

        var content: String?
    }

    enum QuestionType: String, CaseIterable {
        case location = "定位问题"
        case watermark = "水印问题"
        case takePhoto =  "拍摄问题"
        case other = "其他问题或建议"
        
        var type: String {
            switch self {
            case .location:
                return "2"
            case .watermark:
                return "1"
            case .takePhoto:
                return "3"
            case .other:
                return "4"
            }
        }
    }
}

// MARK: - [WmcFeedbackVM]

class WmcFeedbackVM: WmcBaseVM {
    // Internal

    /// 数据列表
    var dataList: [[CellModel]] = []

    var questionType: QuestionType?

    var contact: String?

    var describe: String?

    var images: [UIImage] = []

    // MARK: 其他
    var lockSubmit: Bool = true
    
    private(set) var wechatModel: WmcWechatModel?

    /// 加载数据
    func loadList() {
        var list: [[CellModel]] = []
        // 组1
        let item = CellModel(title: "问题类型", style: .arrow, actionType: .sheet)
        if let questionType = questionType  {
            item.content = questionType.rawValue
        }
        let group_0: [CellModel] = [
            item,
        ]
        list.append(group_0)

        // 组2
        let group_1: [CellModel] = [
            .init(title: "请描述你的问题", style: .input, rowHeight: 180.wmc_autoVer),
        ]
        list.append(group_1)

        // 组3
        let group_2: [CellModel] = [
            .init(title: "联系方式(选填)", style: .textField),
        ]
        list.append(group_2)

        dataList = list
    }

    func fetchFeedback() -> Observable<WmcWechatModel> {
        return WmcOtherAPI.fetchEnterpriseWechat().do { model in
            self.wechatModel = model
        }
    }

    func submit() {
        guard lockSubmit else { return }
        lockSubmit = false
        guard let questionType = questionType else {
            WmcHudManager.toast("请选择问题类型")
            lockSubmit = true
            return
        }

        guard let describe = describe else {
            WmcHudManager.toast("请描述您的问题")
            lockSubmit = true
            return
        }

        if self.images.isEmpty {
            feedback(nil)
        } else {
            var tasks: [(data: Data, fileName: String)] = []
            images.forEach { image in
                if let imgData = image.yp.jpegData(compressed: 0.5) {
                    let key = self.createObjectKey()
                    tasks.append((data: imgData, fileName: key))
                }
            }

            YPNetworkUploadRequest.multiUploadTasks(tasks) { response in
                var imgUrls: [String] = []
                response.forEach { item in
                    imgUrls.append(item.imageName)
                }
                feedback(imgUrls)
            } failure: { [weak self] error in
                guard let weakSelf = self else { return }
                WmcHudManager.toast("提交失败")
                weakSelf.lockSubmit = true
            }
        }
        
        func feedback(_ images: [String]?) {
            WmcOtherAPI.submitFeedback(phone: self.contact ?? "", type: questionType.type, content: describe, imageUrl: images).subscribe { [weak self] _ in
                guard let weakSelf = self else { return }
                YPApp.CurrentVC?.navigationController?.popViewController(animated: true)
                WmcHudManager.toast("提交成功")
                weakSelf.lockSubmit = true
            } onError: { [weak self] error in
                guard let weakSelf = self else { return }
                WmcHudManager.toast("提交失败")
                weakSelf.lockSubmit = true
            }.disposed(by: self.rx.disposeBag)
        }
    }

    func createObjectKey() -> String {
        let date = WmcDateManager.shared.networkDate.value ?? Date()
        let imgName = createImgName(date: date)
        let dateFolderName = date.yp.string("yyyyMMdd")
        let objectKey = "ios/\(dateFolderName)/\(imgName)"
        return objectKey
    }

    // Private
    private func createImgName(date: Date) -> String {
        let arcStr: String = date.timeIntervalSince1970.yp.string.yp.replacing(".", with: "_")
        guard let account: WmcAccountModel = WmcLoginManager.shared.wmcAccountModel else { return "\(arcStr).jpeg" }
        let uid = account.memberId
        let uuid = UUID().uuidString
        return "\(arcStr)\(uid)_\(uuid).png"
    }
}
